package com.zk.config.api.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.log4j.Logger;

public class ComUtil {
	private static Logger logger = Logger.getLogger(ComUtil.class);
	
	/**
	 * 删除目录
	 * @param file
	 * @return
	 */
	public static boolean deleteFolder(File file) {
		if (file != null && file.exists()) {
			if (file.isFile()) {
				if(!file.delete()) {
					return false;
				}
			} else {
				File[] files = file.listFiles();
				if (files != null && files.length > 0) {
					for(File f:files) {
						deleteFolder(f);
					}
				}
				if(!file.delete()) {
					return false;
				}
			}
		}

		return true;
	}
	
	/**
	 * 写内容到指定文件中
	 * @param file
	 * @param content
	 * @return
	 */
	public static boolean writeFile(File file, String content){
		boolean result = false;
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(file));
			writer.write(content);
			writer.close();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("writeFile error!" + e.getMessage());
		}
		return result;
	}
	
	/**
	 * 获得指定文件的内容
	 * @param file
	 * @return
	 */
	public static String readFile(File file){
		StringBuilder content = new StringBuilder();
		try {
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String str;
			while((str = reader.readLine()) != null) {
				content.append(str).append("\n");
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("readFile error!" + e.getMessage());
		}
		return content.toString();
	}
}
